package com.example.cloudzuul.web;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        // LocalThread
        // 获取当前请求上下文对象
        RequestContext requestContext = RequestContext.getCurrentContext();
        final HttpServletRequest request = requestContext.getRequest();
        // 获取资源路径
        final String path = request.getServletPath();
        System.out.println("path = " + path);
        if("/idx/index".equals(path) || "/odr/order".equals(path)){
            return true;
        } else {
            return false;
        }
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext();
        final HttpServletRequest request = requestContext.getRequest();
        // 获取令牌
        final String token = request.getParameter("token");
        // 注意: 这里未验证令牌的内容合法性, 只判断是否有令牌
        if(token==null){
            // 设置zuul响应, 终止对目标资源的访问
            requestContext.setSendZuulResponse(false);
            // 结果码
            requestContext.setResponseStatusCode(401);
            // 响应体
            requestContext.setResponseBody("{\"code\":1,\"msg\":\"token is empty!\"}");
        }
        // 返回值不需要定义
        return null;
    }
}
